package vip.xiaonuo.smzq.modular.kcl.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.URLDecoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.util.CommonFileUtil;
import vip.xiaonuo.smzq.core.tools.file.FileRename;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb01Zh;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb01ZhMapper;
import vip.xiaonuo.smzq.modular.kcl.entity.Wjglb;
import vip.xiaonuo.smzq.modular.kcl.entity.Zlsc;
import vip.xiaonuo.smzq.modular.kcl.entity.Zsk;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.Zlxqcx;
import vip.xiaonuo.smzq.modular.kcl.mapper.WjglbMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.ZlscMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.ZskMapper;
import vip.xiaonuo.smzq.modular.kcl.service.IWjglbService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import vip.xiaonuo.common.page.CommonPageRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;

/**
 * 资料上传文件关联表 服务实现类
 *
 * @author sqq
 * @since 2024-03-13
 */
@Service
public class WjglbServiceImpl extends ServiceImpl<WjglbMapper, Wjglb> implements IWjglbService {

    @Resource
    private ZlscMapper zlscMapper; //资料盒

    @Resource
    private WjglbMapper wjglbMapper;//文件上传关联

    @Resource
    private Cb01ZhMapper cb01ZhMapper;//字典综合1

    @Autowired
    protected HttpServletResponse response;
    @Resource
    private ZskMapper zskMapper;

    @Value("${file.base}")
     String baseFilePath;
    @Override
    public Page<Wjglb> page(Wjglb wjglb) {
        QueryWrapper<Wjglb> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<Zlxqcx> getZlxqcxList(Integer djflbm, String kqbm, Integer nd) {
        List<Zlxqcx> zlxqcxList = new ArrayList<>();
try{
    QueryWrapper<Zlsc> zlscQuery = new QueryWrapper<>();
    zlscQuery.eq("djflbh", djflbm).eq("kqbh", kqbm).eq("nd", nd);
    List<Zlsc> zlscList = zlscMapper.selectList(zlscQuery);
    for (Zlsc zlsc : zlscList) {
        QueryWrapper<Wjglb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("djflbh", djflbm).eq("kqbh", kqbm).eq("nd", nd).eq("zlsc_id", zlsc.getPkid());
        List<Wjglb> wjglbList = wjglbMapper.selectList(queryWrapper);
        for (Wjglb wjglb : wjglbList) {
            Zlxqcx zlxqcx = new Zlxqcx();
            zlxqcx.setPkid(wjglb.getPkid());
            //矿业权库类型
            zlxqcx.setKyqklx(zlsc.getKyqklx());
            //矿业权登记类型
            zlxqcx.setKyqdjlx(zlsc.getKyqdjlx());
            //节点类型
            zlxqcx.setJdlx(zlsc.getJdlx());
            //资料性质
            zlxqcx.setZlxz(zlsc.getZlxz());
            zlxqcx.setWjbh(wjglb.getWjbh());
            zlxqcx.setWjmc(wjglb.getWjmc());
            zlxqcx.setWjhz(wjglb.getWjhz());
            zlxqcx.setWjlj(wjglb.getWjlj());
            zlxqcx.setKqbh(wjglb.getKqbh());
            zlxqcx.setDjflbh(wjglb.getDjflbh());
            zlxqcx.setNd(wjglb.getNd());
            zlxqcx.setZlsxh(wjglb.getZlsxh());
            zlxqcx.setZlsj(zlsc.getZlsj());
            zlxqcxList.add(zlxqcx);
            zlxqcx.setZlsj(zlsc.getZlsj());
        }
    }
}catch (Exception e){
    e.printStackTrace();
}

        return zlxqcxList;
    }

    @Override
    public String fileUpload(MultipartFile file) {

        String time = DateUtil.format(new Date(), "YYYY-MM-dd");
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        String fbr = saBaseLoginUser.getName();
        //文件名称
        String fileName = file.getOriginalFilename();
        File file1 = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);//解码
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String wjName = fileName.substring(0, fileName.lastIndexOf("."));
        //设置文件清单主键id
        String uuidfile = UUID.randomUUID().toString();
        String filePath = file1.getPath();
        filePath = filePath.substring(0, filePath.lastIndexOf("\\"));

        //目标文件路径
        filePath=filePath+"\\"+uuidfile+suffix;
        FileRename.fileRename(file1.getPath(),filePath);
       File newFile=new File(filePath);
        if (newFile.exists()){
            Wjglb wjglb = new Wjglb();
            wjglb.setPkid(uuidfile);
            wjglb.setWjmc(wjName);
            wjglb.setWjhz(suffix);
            wjglb.setWjdx(Math.toIntExact(file1.length()));
            wjglb.setWjlj(filePath);
            wjglb.setWjsclj(filePath);
            wjglb.setScsj(time);
            wjglb.setScr(fbr);
            int fileCount = wjglbMapper.insert(wjglb);
            if (fileCount > 0) {
                return uuidfile;

            }
        }

        return "";
    }

    @Override
    public void filesDownload(String fileId) {
        String zipName = DateUtil.format(new Date(), "YYYYMMdd");
        String zipPath = PathUtils.getUpLoadPath(baseFilePath) + File.separator + zipName + ".zip";
        List<String> fileIdList = Arrays.asList(fileId.split(","));
        List<File> fileList = new ArrayList<>();
        if (fileIdList.size() > 0) {
            QueryWrapper<Wjglb> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("pkid", fileIdList);
            List<Wjglb> wjglbList = wjglbMapper.selectList(queryWrapper);
            if (wjglbList != null && wjglbList.size() > 0) {
                for (Wjglb wjglb : wjglbList) {
                    String filePath = wjglb.getWjlj();
                    filePath = filePath.substring(0, filePath.lastIndexOf("\\"));
                    Zsk zsk = zskMapper.selectById(wjglb.getZlscId());
                    //目标文件路径
                   // filePath=filePath+"\\"+zsk.getWjmc()+"+"+zsk.getPkid()+wjglb.getWjhz();
                    filePath=filePath+"\\"+zsk.getWjmc()+wjglb.getWjhz();
                    try {
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        FileRename.copyFileUsingStreams(wjglb.getWjlj(),filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    File file = new File(filePath);
                    if (file.exists()) {
                        fileList.add(file);
                    }

                }
            }
        }
        //如果是单个文件直接返回
        if (fileList.size() == 1) {
            PathUtils.singleFileShow(fileList.get(0).getPath(), response);
        }
        //如果是多个则返回zip
        if (fileList.size() > 1) {
            CommonFileUtil.compressFilesToZip(fileList, zipPath);
            PathUtils.singleFileShow(zipPath, response);

        }
        File file = new File(zipPath);
        if (file.exists()) {
            file.delete();
        }
    }

}
